package com.javaweb.admin.config;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.javaweb.admin.vo.cgfp.CGFPInfo;
import com.javaweb.admin.entity.Scheduled;
import com.javaweb.admin.mapper.ScheduledMapper;
import com.javaweb.admin.service.AbstractJob;
import com.javaweb.admin.service.ICGFPService;
import com.javaweb.admin.service.INcTaskLogService;
import com.javaweb.common.config.CommonConfig;
import com.javaweb.common.utils.HttpUtils;
import com.javaweb.common.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.List;

@Component
public class UploadCGFP2BIPJob extends AbstractJob {
    @Autowired
    ScheduledMapper scheduledMapper;

    @Autowired
    INcTaskLogService iNcTaskLogService;

    @Autowired
    ICGFPService iCGFPService;

    @Override
    public String getName() {
        QueryWrapper<Scheduled> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("classpath",this.getClass().getName());
        Scheduled entity = scheduledMapper.selectOne(queryWrapper);
        return entity.getName();
    }

    @Override
    public void execute() {
        try {
            //获取待上传发票
            List<CGFPInfo> fpList = iCGFPService.getCGFPList();
            //获取access_token
            String token = getToken();

            for(CGFPInfo fp :fpList) {
                iCGFPService.cgfpToBIP(fp, token);
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        System.out.println("测试采购发票上传");
    }

    public String getToken(){
        JsonResult jsonResult = new JsonResult();
        long timestamp = System.currentTimeMillis();
        StringBuilder parameterMap = new StringBuilder();
        parameterMap.append("appKey");
        parameterMap.append(CommonConfig.bipAppkey);
        parameterMap.append("timestamp");
        parameterMap.append(String.valueOf(timestamp));
        String signature = getSignature(parameterMap.toString(), CommonConfig.bipAppsecret);
        StringBuilder param = new StringBuilder();
        param.append("appKey=");
        param.append(CommonConfig.bipAppkey);
        param.append("&timestamp=");
        param.append(String.valueOf(timestamp));
        param.append("&signature=");
        param.append(signature);
        String tokenJson = HttpUtils.sendGet(CommonConfig.bipAccessTokenUrl, param.toString());
        String token = JSONObject.parseObject(tokenJson).getJSONObject("data").getString("access_token");
        return token;
    }

    public String getSignature(String data, String secret){
        try {
            // Create HmacSha256 Key
            SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");

            // Get an instance of Mac object implementing HmacSha256 operation
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(secretKeySpec);

            // Calculate the HMAC value
            byte[] hmacBytes = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
            String hmacHex = Base64.getEncoder().encodeToString(hmacBytes);
            String signature = URLEncoder.encode(hmacHex, "UTF-8");
            return signature;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}